import $ from "jquery";

!(function (Jq_Ajax) {
    if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {

        define(Jq_Ajax);
    } else if (typeof module !== 'undefined' && module.exports) {
        module.exports = Jq_Ajax();
    } else {
        window.Jq_Ajax = Jq_Ajax();
    }
})(function () {

    function Jq_Ajax(setting) {
        this.url = setting.url;
        this.data = setting.data;
        this.callback = setting.callback;
        this.error = setting.error;

        this.init();
    }

    Jq_Ajax.prototype.init = function () {

        const host = "//api.mp.tianshunet.com/kongtongapp/";

        this.jsonp(host, this.url, this.data, this.callback, this.error);
    }

    /**
     *  传递参数合并
     */
    Jq_Ajax.prototype._getData = function (data, callback) {

        const appkey = "1476783185000";
        const versionCode = "1";
        const type = "3";

        if (data == null) {
            data = {};
        }
        var timestamp = Date.parse(new Date());
        data.appkey = appkey;
        data.versionCode = versionCode;
        data.randomCode = timestamp;
        data.type = type;
        //      data.token = rootScope.getToken(); // token 参数
        data.callbackfun = callback;
        return data;
    }

    /**
     *  ajax请求合并
     */
    Jq_Ajax.prototype._getCommonOpt = function (host, url, data, callback, error) {
        var data = this._getData(data, callback);
        return {
            url: host + url,
            data: data,
            error: error
        }
    }

    /**
     *  jsonp请求
     */
    Jq_Ajax.prototype.jsonp = function (host, url, data, callback, error) {
        var opt;
        opt = this._getCommonOpt(host, url, data, callback, error);
        opt.type = 'GET';
        opt.dataType = 'JSONP';
        opt.contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
        return this._sendRequst(opt);
    }

    Jq_Ajax.prototype._sendRequst = function (opt) {
        var obj = {
            url: opt.url,
            type: opt.type,
            data: opt.data,
            dataType: opt.dataType,
            contentType: opt.contentType,
            timeout: opt.timeout || 50000,
            beforeSend: function (xhr) { },
            success: function (res) {
                opt.callback(res);
            },
            error: function (err) {
                opt.error(err);
                // opt.error && 
            }
        }
        return $.ajax(obj);
    }
    return Jq_Ajax;
});


